import { ResultPage } from 'antd-mobile'
import { SearchBar } from 'antd-mobile'
import { NoticeBar } from 'antd-mobile'
import img from '../../img/预约挂号.png'
import img1 from '../../img/复诊开方.png'
import img2 from '../../img/极速问诊.png'
import img3 from '../../img/问专家.png'
import img4 from '../../img/开药门诊.png'
import img5 from '../../img/直播.png'
import img6 from '../../img/科普.png'
import img7 from '../../img/买药.png'
import { useState, useEffect, useMemo, useCallback } from 'react'
import http from '../../api/index'
import style from './index.module.css'
import DoctorList from '../../conpoment/DoctorList'
import ServiceCard from '../../conpoment/ServiceCard'
import { CapsuleTabs } from 'antd-mobile'
import { useNavigate } from 'react-router-dom';
import Yaopin_xq from '../../conpoment/yaopin_xq'
import List_todo1 from '../../conpoment/List_todo1'
// 医生数据接口
interface DoctorData {
    id: number;
    doctorname: string;
    doctorcity: string;
    doctoradministre: string;
    socoadmin: string;
    doctorimage: string;
    doctorgood: number;
    doctorbrowse: number;
    department?: string;
}
// 药品数据接口
interface DrugData {
    id: number;
    restorativesimage: string;
    restorativesname: string;
    restorativesstate: string;
    restorativesprice: number;
}
function Index() {
    // 状态管理
    const [activeTab, setActiveTab] = useState('1');
    const [, setDoctorsData] = useState<DoctorData[]>([]);
    const [doctorsByDepartment, setDoctorsByDepartment] = useState<{ [key: string]: DoctorData[] }>({});
    const [list, setList] = useState<DrugData[]>([]);
    // 缓存相关状态
    const [isDataCached, setIsDataCached] = useState<boolean>(false);
    // 缓存配置 - 5分钟过期
    const CACHE_DURATION = 5 * 60 * 1000; // 5分钟
    // 缓存工具函数
    const getCacheKey = (key: string) => `home_cache_${key}`;
    const setCache = useCallback((key: string, data: any) => {
        const cacheData = {
            data,
            timestamp: Date.now()
        };
        localStorage.setItem(getCacheKey(key), JSON.stringify(cacheData));
        setIsDataCached(true);
    }, []);
    const getCache = useCallback((key: string) => {
        try {
            const cached = localStorage.getItem(getCacheKey(key));
            if (cached) {
                const cacheData = JSON.parse(cached);
                const now = Date.now();
                // 检查缓存是否过期
                if (now - cacheData.timestamp < CACHE_DURATION) {
                    console.log(`使用缓存数据: ${key}`);
                    return cacheData.data;
                } else {
                    localStorage.removeItem(getCacheKey(key));
                }
            }
        } catch (error) {
            console.error('读取缓存失败:', error);
        }
        return null;
    }, [CACHE_DURATION]);
    const clearCache = useCallback(() => {
        const keys = ['doctors', 'drugs'];
        keys.forEach(key => {
            localStorage.removeItem(getCacheKey(key));
        });
        setIsDataCached(false);
    }, []);
    // 科室配置
    const departments = [
        { key: '1', name: '妇产科', department: '妇产科' },
        { key: '2', name: '儿科', department: '儿科' },
        { key: '3', name: '皮肤科', department: '皮肤科' },
        { key: '4', name: '心血管内科', department: '心血管内科' },
        { key: '5', name: '呼吸内科', department: '呼吸内科' },
        { key: '6', name: '消化内科', department: '消化内科' },
        { key: '7', name: '中医科', department: '中医科' },
        { key: '8', name: '口腔科', department: '口腔科' },
    ];
    const getData = async () => {
        try {
            // 首先尝试从缓存获取数据
            const cachedDoctors = getCache('doctors');
            if (cachedDoctors) {
                console.log('使用缓存的医生数据');
                setDoctorsData(cachedDoctors.doctors);
                setDoctorsByDepartment(cachedDoctors.groupedDoctors);
                return;
            }
            const res = await http.get('/api/doctor/list', {
                params: {
                    page: 1,
                    pageSize: 100,
                    limit: 100,
                    size: 100
                }
            });
            console.log('API响应:', res.data);
            // 解析数据
            let doctors: DoctorData[] = [];
            if (res.data.data) {
                doctors = Array.isArray(res.data.data) ? res.data.data : res.data.data.list || [];
            } else if (res.data.list) {
                doctors = res.data.list;
            } else if (Array.isArray(res.data)) {
                doctors = res.data;
            }
            console.log('解析后的医生数据:', doctors);
            setDoctorsData(doctors);
            // 按科室分组数据，100条数据平均分配到8个科室
            const groupedDoctors: { [key: string]: DoctorData[] } = {};
            const doctorsPerDepartment = 2; // 每个科室只分配2条数据
            let usedDoctorIndices = new Set<number>();
            console.log(`总共获取${doctors.length}条数据，每个科室分配${doctorsPerDepartment}条数据`);
            departments.forEach((dept) => {
                let departmentDoctors: DoctorData[] = [];
                // 首先尝试从API数据中过滤该科室的真实数据
                const filteredDoctors = doctors.filter((doctor: DoctorData) =>
                    doctor.department === dept.department
                );
                if (filteredDoctors.length >= doctorsPerDepartment) {
                    // 如果该科室有足够的数据，取指定数量
                    departmentDoctors = filteredDoctors.slice(0, doctorsPerDepartment);
                    console.log(`${dept.department}科室使用真实数据:`, filteredDoctors.length, '条，取前2条');
                } else if (filteredDoctors.length > 0) {
                    // 如果该科室数据不足，用现有数据
                    departmentDoctors = filteredDoctors;
                    console.log(`${dept.department}科室使用部分真实数据:`, filteredDoctors.length, '条');
                } else {
                    // 如果该科室没有真实数据，从总数据中分配不同的数据
                    const availableDoctors = doctors.filter((_, idx) => !usedDoctorIndices.has(idx));
                    const doctorsToAssign = Math.min(doctorsPerDepartment, availableDoctors.length);
                    departmentDoctors = availableDoctors.slice(0, doctorsToAssign).map((doctor: DoctorData) => {
                        const originalIndex = doctors.indexOf(doctor);
                        usedDoctorIndices.add(originalIndex);
                        return {
                            ...doctor,
                            department: dept.department,
                            doctorcity: doctor.doctorcity || '北京',
                            doctoradministre: doctor.doctoradministre || '主任医师',
                            socoadmin: doctor.socoadmin || '三甲医院'
                        };
                    });
                    console.log(`${dept.department}科室分配模拟数据:`, doctorsToAssign, '条');
                }
                groupedDoctors[dept.department] = departmentDoctors;
                console.log(`${dept.department}科室最终数据:`, departmentDoctors.length, '条');
            });
            setDoctorsByDepartment(groupedDoctors);
            // 缓存数据
            setCache('doctors', {
                doctors,
                groupedDoctors
            });
        } catch (error: any) {
            console.error('获取医生数据失败:', error);
        }
    };
    const getlist = async () => {
        try {
            // 首先尝试从缓存获取数据
            const cachedDrugs = getCache('drugs');
            if (cachedDrugs) {
                console.log('使用缓存的药品数据');
                setList(cachedDrugs);
                return;
            }
            console.log('开始获取药品数据...');
            const res = await http.get('/api/restorative/list', {
                params: {
                    page: 1,
                    pageSize: 16,
                    limit: 16,
                    size: 16
                }
            })
            console.log('药品数据响应:', res.data);
            setList(res.data.data);
            // 缓存数据
            setCache('drugs', res.data.data);
        } catch (error: any) {
            console.error('获取药品数据失败:', error);
        }
    }
    useEffect(() => {
        getData();
        getlist()
    }, []);
    // 动态生成tabs配置 - 使用useMemo确保数据更新时重新创建
    const items = useMemo(() => [
        {
            key: '1',
            label: '妇产科',
            department: '妇产科'
        },
        {
            key: '2',
            label: '儿科',
            department: '儿科'
        },
        {
            key: '3',
            label: '皮肤科',
            department: '皮肤科'
        },
        {
            key: '4',
            label: '心血管内科',
            department: '心血管内科'
        },
        {
            key: '5',
            label: '呼吸内科',
            department: '呼吸内科'
        },
        {
            key: '6',
            label: '消化内科',
            department: '消化内科'
        },
        {
            key: '7',
            label: '中医科',
            department: '中医科'
        },
        {
            key: '8',
            label: '口腔科',
            department: '口腔科'
        },
    ], []);

    const onChange = (key: string) => {
        setActiveTab(key);
    };
    const data = [
        {
            title: '预约挂号',
            img: img,
            text: '30W+专家入驻'
        },
        {
            title: '极速问诊',
            img: img2,
            text: '平均3分钟接诊'
        },
        {
            title: '复诊开方',
            img: img1,
            text: '慢病续方送到家'
        }
    ]
    const data1 = [
        {
            title: '问专家',
            imgs: img3,
        },
        {
            title: '开药门诊',
            imgs: img4,
        },
        {
            title: '义诊直播',
            imgs: img5,
        },
        {
            title: '健康科普',
            imgs: img6,
        },
        {
            title: '商城买药',
            imgs: img7,
        },
        {
            title: '人脸识别',
            imgs: img7, // 使用现有图标，可以后续替换
        },

    ]
    const nav = useNavigate()
    return (
        <div>
            <ResultPage
                status=''
                title=''
                description={
                    <div className={style.pageTitle}>
                        妙手医生<span className={style.brandName}>·妙手互联网医院</span>
                    </div>
                } >
                <ResultPage.Card className={style.searchCard}>
                    <div onClick={() => nav('/home_ss')}>
                        <SearchBar placeholder='搜索医生、医院、药品、疾病症状' />
                    </div>
                </ResultPage.Card>
                <div className={style.noticeContainer}>
                    <NoticeBar content='适用于当前页面内信息的通知，是一种较醒目的页面内通知方式' color='alert' />
                </div>
                <div className={style.bigbox}>
                    <div className={style.serviceCardsContainer}  onClick={()=>nav('/Wenz')}>
                        {data.map((item, index) => (
                            <ServiceCard
                                key={index}
                                title={item.title}
                                img={item.img}
                                text={item.text}
                            />
                        ))}
                    </div>
                    <div className={style.pp}>
                        {data1.map((item, index) => (
                            <ServiceCard
                                key={index}
                                title={item.title}
                                img={item.imgs}
                                className={style.serviceCard}
                                titleClassName={style.serviceTitles}
                            />
                        ))}
                    </div>
                </div>
                <div>
                    <Yaopin_xq />
                </div>
                <div className={style.expertSection}>
                    <h4 className={style.expertTitle}>我要问专家
                        <span className={style.moreLink}>更多＞</span></h4>
                    <div className={style.expertList}>
                        <div className={style.capsuleTabsWrapper}>
                            <CapsuleTabs activeKey={activeTab} onChange={onChange}>
                                {items.map(item => (
                                    <CapsuleTabs.Tab key={item.key} title={item.label}>
                                        <DoctorList
                                            department={item.department}
                                            initialDoctors={doctorsByDepartment[item.department] || []}
                                        />
                                    </CapsuleTabs.Tab>
                                ))}
                            </CapsuleTabs>
                        </div>
                    </div>
                </div>
                
                <div className={style.expertSection}>
                    <p>我要买药 <span className={style.moreLink}>更多＞</span></p>
                    <div className={style.capsuleTabsWrapper}>
                        <CapsuleTabs>
                            <CapsuleTabs.Tab title='皮肤用药' key='fruits'>
                                <div className={style.drugListContainer}>
                                    {list.slice(0, 4).map((item, index) => (
                                        <div key={index} className={style.expertItem}>
                                            <img src={item.restorativesimage} alt="" className={style.img} />
                                            <p>{item.restorativesname}</p>
                                            <p>{item.restorativesstate}</p>
                                            <p style={{ color: '#FF0000', fontWeight: 'bold' }}>￥{item.restorativesprice}</p>
                                        </div>
                                    ))}
                                </div>
                            </CapsuleTabs.Tab>
                            <CapsuleTabs.Tab title='男科用药' key='vegetables'>
                                <div className={style.drugListContainer}>
                                    {list.slice(4, 8).map((item, index) => (
                                        <div key={index + 4} className={style.expertItem}>
                                            <img src={item.restorativesimage} alt="" className={style.img} />
                                            <p>{item.restorativesname}</p>
                                            <p>{item.restorativesstate}</p>
                                            <p style={{ color: '#FF0000', fontWeight: 'bold' }}>￥{item.restorativesprice}</p>
                                        </div>
                                    ))}
                                </div>
                            </CapsuleTabs.Tab>
                            <CapsuleTabs.Tab title='妇科用药' key='animals'>
                                <div className={style.drugListContainer}>
                                    {list.slice(8, 12).map((item, index) => (
                                        <div key={index + 8} className={style.expertItem}>
                                            <img src={item.restorativesimage} alt="" className={style.img} />
                                            <p>{item.restorativesname}</p>
                                            <p >{item.restorativesstate}</p>
                                            <p style={{ color: '#FF0000', fontWeight: 'bold' }}>￥{item.restorativesprice}</p>
                                        </div>
                                    ))}
                                </div>
                            </CapsuleTabs.Tab>
                            <CapsuleTabs.Tab title='儿科用药' key='ert'>
                                <div className={style.drugListContainer}>
                                    {list.slice(12, 16).map((item, index) => (
                                        <div key={index + 12} className={style.expertItem}>
                                            <img src={item.restorativesimage} alt="" className={style.img} />
                                            <p>{item.restorativesname}</p>
                                            <p>{item.restorativesstate}</p>
                                            <p style={{ color: '#FF0000', fontWeight: 'bold' }}>￥{item.restorativesprice}</p>
                                        </div>
                                    ))}
                                </div>
                            </CapsuleTabs.Tab>
                        </CapsuleTabs>
                    </div>
                </div>
                <div style={{ marginTop: '20px',background:'#fff' }}>
                    <h4>为您推荐</h4>
                    <List_todo1/>9
                </div>
                <div className={style.cacheStatus}>
                    
                    {isDataCached && (
                        <button 
                            className={style.clearCacheBtn}
                            onClick={clearCache}
                        >
                            清空缓存
                        </button>
                    )}
                </div>
                <div className={style.dingwei} onClick={()=>nav('/dingwei')}>
                   {localStorage.getItem('selectedCity')||'获取定位...'}
                </div>
            </ResultPage>
        </div>
    )   
}
export default Index